<template>
  <div class="user-cls">
    <el-form
      :model="form"
      ref="formObj"
      :rules="rules"
      label-width="100px"
      :inline="false"
    >
      <el-form-item label="手机号码：" prop="phonenumber">
        <el-input v-model="form.phonenumber" maxlength="11"></el-input>
      </el-form-item>
      <el-form-item label="用户邮箱：" prop="email">
        <el-input v-model="form.email" maxlength="50"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          class="btn-cls"
          @click="savaHandler"
          v-hasPerm="['system:user:updateBaseInfo']"
          >保存</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, defineProps } from "vue";
import { useStore } from "vuex";
import request from "@/utils/request";
import { ElMessage } from "element-plus";

const store = useStore();
const props = defineProps({
  user: {
    type: Object,
    required: true,
    default: () => {
      return {};
    },
  },
});
const form = ref({
  id: -1,
  phonenumber: "",
  email: "",
});
form.value = props.user;
const formObj = ref(null);
const mobileReg = /^1[38]\d|5[0-35-9]|7[3678]\d{8}$/;
const emailReg = /^[a-zA-Z0-9]+@[a-zA-Z0-9]+\.[a-zA-Z0-9]+$/;

const validateMobile = (rule, value, callback) => {
  if (value && !mobileReg.test(value)) {
    return callback(new Error("请输入11位手机号码格式"));
  } else {
    // 校验通过
    callback();
  }
};
const validateEmail = (rule, value, callback) => {
  if (value && !emailReg.test(value)) {
    return callback(new Error("请输入仅包含字母和数字的电子邮件"));
  } else {
    // 校验通过
    callback();
  }
};
const rules = ref({
  phonenumber: [
    { required: true, message: "电话号码不能为空", trigger: "blur" },
    {
      validator: validateMobile,
      trigger: "blur",
    },
  ],
  email: [
    { required: true, message: "邮箱不能为空", trigger: "blur" },
    {
      validator: validateEmail,
      trigger: "blur",
    },
  ],
});
const savaHandler = () => {
  formObj.value.validate(async (isValid, invalidFields) => {
    if (isValid) {
      console.log("验证通过");
      let result = await request.post("sys/user/save", form.value);
      let data = result.data;
      if (data.code == 200) {
        ElMessage.success("保存成功");
      }
    } else {
      console.log("验证失败");
    }
  });
};
</script>

<style lang="less" scoped>
.user-cls {
  width: 60%;
  height: 100%;
}
.btn-cls {
  width: 120px;
  button {
    width: 100%;
    height: 100%;
  }
}
</style>